<!DOCTYPE html>
<html lang="en-US">
  <head>
    <link href="/assets/index.css" rel="stylesheet" type="text/css" />
    <script crossorigin="anonymous" src="/test-harness.js"></script>
    <script crossorigin="anonymous" src="/test-page-object.js"></script>
    <script crossorigin="anonymous" src="/__dist__/webchat-es5.js"></script>
  </head>
  <body>
    <main id="webchat"></main>
    <script>
      run(async function () {
        const workingDirectLine = WebChat.createDirectLine({ token: await testHelpers.token.fetchDirectLineToken() });
        let firstBotActivityId;
        let firstBotActivityTimestamp;

        const directLine = {
          activity$: workingDirectLine.activity$.map(activity => {
            if (!activity.channelData && activity.type === 'message') {
              // Duplicate the ID using the first message activity from bot.

              if (firstBotActivityId) {
                return Object.assign({}, activity, {
                  id: firstBotActivityId,
                  timestamp: firstBotActivityTimestamp
                });
              }

              firstBotActivityId = activity.id;
              firstBotActivityTimestamp = activity.timestamp;
            }

            return activity;
          }),
          connectionStatus$: workingDirectLine.connectionStatus$,
          postActivity: workingDirectLine.postActivity.bind(workingDirectLine),
          token: workingDirectLine.token
        };

        WebChat.renderWebChat(
          {
            directLine,
            store: testHelpers.createStore()
          },
          document.getElementById('webchat')
        );

        await pageConditions.uiConnected();

        // WHEN: An "echo" message is being sent to the bot.
        await pageObjects.sendMessageViaSendBox('echo This message will be replaced by a carousel.', {
          waitForSend: true
        });

        // THEN: Bot should reply with 2 messages. However, we change their `activity.id` to be the same value.
        //       Thus, only the second message will be shown. And there are 2 messages in total only.
        await pageConditions.numActivitiesShown(2);

        // THEN: It should show 1 outgoing message, and 1 incoming message.
        await host.snapshot();

        // WHEN: A "carousel" message is being sent.
        await pageObjects.sendMessageViaSendBox('carousel', { waitForSend: true });

        // THEN: It should show 2 messages only because all messages from bot is being collapsed into a single message.
        await pageConditions.numActivitiesShown(3);

        // WHEN: All images (in the carousel) are loaded.
        await pageConditions.allImagesLoaded();

        // WHEN: Scroll to bottom completed.
        await pageConditions.scrollToBottomCompleted();

        // THEN: It should show 3 messages: 2 outgoing messages and 1 incoming message (carousel).
        await host.snapshot();
      });
    </script>
  </body>
</html>
